import datetime
from flask import Blueprint, render_template, request, jsonify,session
from flask_login import login_required, current_user
from sqlalchemy import desc
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Memberrole
from applications.schemas import MmberRoleSchema2



admin_memberrole = Blueprint('adminMemberRole', __name__, url_prefix='/admin/memberrole')


# 用户管理
@admin_memberrole.get('/')
@authorize("admin:memberrole:main")
def main():

    return render_template('admin/memberrole/main.html')


# 表格数据
@admin_memberrole.get('/data')
@authorize("admin:memberrole:main")
def table():
    name = str_escape(request.args.get('realName', type=str))
    filters = []
    if name:
        filters.append(Memberrole.rolename.contains(name))
    Memberroles = Memberrole.query.filter(*filters).layui_paginate()
    return table_api(
        data=[{
            'id': Memberrole.id,
            'rolename': Memberrole.rolename,
            'create_time': Memberrole.create_time,
            'update_time': Memberrole.update_time,
        } for Memberrole in Memberroles.items],
        count=Memberroles.total)

# 角色增加
@admin_memberrole.get('/add')
@authorize("admin:memberrole:add", log=True)
def add():
    return render_template('admin/memberrole/add.html')


# 角色增加
@admin_memberrole.post('/save')
@authorize("admin:memberrole:add", log=True)
def save():
    req = request.get_json(force=True)
    details = str_escape(req.get("details"))
    roleName = str_escape(req.get("roleName"))
    create_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    sort = str_escape(req.get("sort"))
    if not roleName:
        return fail_api(msg="用户组名称不能为空")
    if not sort:
        return fail_api(msg="用户组排序不能为空")
    if not details:
        return fail_api(msg="用户组描述不能为空")
    role = Memberrole(
        details=details,
        rolename=roleName,
        create_time=create_time,
        sort=sort
    )
    db.session.add(role)
    db.session.commit()
    return success_api(msg="成功")

# 角色编辑
@admin_memberrole.get('/edit/<int:id>')
@authorize("admin:memberrole:edit", log=True)
def edit(id):
    r = get_one_by_id(model=Memberrole, id=id)
    return render_template('admin/memberrole/edit.html', memberrole=r)


# 更新角色
@admin_memberrole.put('/update')
@authorize("admin:memberrole:edit", log=True)
def update():
    reqs = request.get_json(force=True)
    id = reqs.get("memberRoleId")
    if not id:
        return fail_api(msg="数据异常，请联系管理员")
    details = str_escape(reqs.get("details"))
    roleName = str_escape(reqs.get("roleName"))
    sort = str_escape(reqs.get("sort"))
    if not roleName:
        return fail_api(msg="用户组名称不能为空")
    if not sort:
        return fail_api(msg="用户组排序不能为空")
    if not details:
        return fail_api(msg="用户组描述不能为空")
    data = {
        "rolename": roleName,
        "sort": sort,
        "details": details
    }
    role = Memberrole.query.filter_by(id=id).update(data)
    db.session.commit()
    if not role:
        return fail_api(msg="更新角色失败")
    return success_api(msg="更新角色成功")

# 角色删除
@admin_memberrole.delete('/remove/<int:id>')
@authorize("admin:memberrole:remove", log=True)
def remove(id):
    role = Memberrole.query.filter_by(id=id).first()
    # 删除该角色的权限和用户
    role.power = []
    role.user = []

    r = Memberrole.query.filter_by(id=id).delete()
    db.session.commit()
    if not r:
        return fail_api(msg="角色删除失败")
    return success_api(msg="角色删除成功")


# 批量删除
@admin_memberrole.delete('/batchRemove')
@authorize("admin:memberrole:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        role = Memberrole.query.filter_by(id=id).first()
        # 删除该角色的权限和用户
        role.power = []
        role.user = []

        r = Memberrole.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")


@admin_memberrole.get('/selectuser')
@authorize("admin:memberrole:main", log=True)
def select_parent():
    role = Memberrole.query.all()
    res = curd.model_to_dicts(schema=MmberRoleSchema2, data=role)
    res.append({"powerId": 0, "powerName": "顶级权限", "parentId": -1})
    res = {
        "status": {"code": 200, "message": "默认"},
        "data": res

    }
    return jsonify(res)


